package main

import (
	"context"
	"fmt"
	"log"
	"yunion.io/x/jsonutils"
	"yunion.io/x/onecloud/pkg/mcclient"
	modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
)

func main() {
	client := mcclient.NewClient("https://api.saltyun.com/api/s/identity/v3", 60, true, true, "", "")
	token, err := client.Authenticate("sysadmin", "N48XSRmcsP5YMcPf", "Default", "system", "Default")
	if err != nil {
		panic(err)
	}

	s := client.NewSession(context.Background(), "region0", "", "apigateway", token)

	// ✅ 修正后的虚拟机参数
	params := jsonutils.NewDict()
	params.Add(jsonutils.NewString("my02"), "name")
	params.Add(jsonutils.NewInt(1), "vcpu_count")   // 设置2核CPU
	params.Add(jsonutils.NewInt(1024), "vmem_size") // 4GB内存
	params.Add(jsonutils.NewString("zone0"), "prefer_zone")
	params.Add(jsonutils.NewString("386b72c9-95e1-4b6f-8124-361a904363cb"), "keypair_id")
	params.Add(jsonutils.NewInt(1), "count")
	params.Add(jsonutils.NewString("hosts-net"), "network")
	params.Add(jsonutils.JSONTrue, "auto_start")

	// ✅ 关键：磁盘配置数组（含boot_index）
	diskSpec := jsonutils.NewArray()
	diskData := jsonutils.NewDict()
	diskData.Add(jsonutils.NewInt(30), "size")
	diskData.Add(jsonutils.NewString("Ubuntu Server-Linux-22.04(Jammy)-x86_64-current"), "image_id")
	diskData.Add(jsonutils.NewString("sys"), "disk_type")
	diskData.Add(jsonutils.NewInt(0), "boot_index") // 标记为启动盘
	diskSpec.Add(diskData)
	params.Add(diskSpec, "disks")

	// ✅ 创建虚拟机
	result, err := modules.Servers.Create(s, params)
	if err != nil {
		log.Fatalf("创建虚拟机失败: %v", err)
	}

	fmt.Println("虚拟机创建成功！")
	fmt.Println(result.PrettyString())
}
